//
//  ArticleCollectionViewController.m
//  Yanwei
//
//  Created by 刘文 on 2017/12/8.
//  Copyright © 2017年 DCloud. All rights reserved.
//

#import "ArticleCollectionViewController.h"
#import "SomeoneZoneSectionTypeArticleCell.h"
#import "ArticleBigImageTypeCell.h"
#import <UIImageView+WebCache.h>
#import "UIAlertView+Block.h"
/**
#import "BasicNavigationController.h"
#import "NewReadArticleDetailViewController.h"
 #import "ReadRequestManager.h"
 */
#import "UITableViewRowAction+JZExtension.h"
#import "UserInfoManager.h"
#import "CollectionBottomView.h"

@interface ArticleCollectionViewController () <UITableViewDelegate, UITableViewDataSource> {
    BOOL _hiddenKeepView;
}

@property (strong, nonatomic) UITableView * tableView;
@property (nonatomic, strong) NullStateView *nullStateView;
@property (strong, nonatomic) CollectionBottomView * collectionBottomView;

@end

@implementation ArticleCollectionViewController

- (void)_reLayout {
    self.navigationView.title = @"文章收藏";
    
    __weakConfigure
    [self.navigationView addNavigationRightView:CGRectMake(0, 0, 55, 40)
                                      titleFont:APPFONT(14)
                                     titleColor:Color100
                                      titleText:@"编辑"
                                        tapBack:^(UIView *v) {
                                            [__weakSelf rightBaritemAction];
                                        }];
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadDataWithPage {
    /**
    [ReadRequestManager newUserCollectionWithPage:self.tableView.page sucess:^(NSArray *data) {
        [self.tableView.dataArray addObjectsFromArray:data];
        if (self.tableView.page == 1) {
            [self.tableView.mj_header endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (data.count == 0 && self.tableView.page == 1) {
            self.tableView.tableFooterView = self.nullStateView;
        } else {
            self.tableView.tableFooterView = [UIView new];
            if (self.tableView.dataArray.count < PageCount || data.count == 0) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            } else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
            }
        }
        self.collectionBottomView.selectedAll = NO;
        self.tableView.page++;
        [self.tableView reloadData];
    } fail:^(NSString *error) {
        [SVProgressHUD showErrorWithStatus:error];
        if (self.tableView.page == 1) {
            [self.tableView.mj_header endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
     */
}

- (void)rightBaritemAction {
    if (self.tableView.dataArray.count == 0) {
        return;
    }
    _hiddenKeepView = !_hiddenKeepView;
    __weakConfigure
    if (!_hiddenKeepView) {
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view);
        }];
        [self.navigationView addNavigationRightView:CGRectMake(0, 0, 55, 40)
                                          titleFont:APPFONT(14)
                                         titleColor:Color100
                                          titleText:@"编辑"
                                            tapBack:^(UIView *v) {
                                                [__weakSelf rightBaritemAction];
                                            }];
    } else {
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.collectionBottomView.mas_top).priorityHigh();
        }];
        [self.navigationView addNavigationRightView:CGRectMake(0, 0, 55, 40)
                                          titleFont:APPFONT(14)
                                         titleColor:Color100
                                          titleText:@"完成"
                                            tapBack:^(UIView *v) {
                                                [__weakSelf rightBaritemAction];
                                            }];
        
        /**
        [self.tableView.dataArray enumerateObjectsUsingBlock:^(ArticleListDataModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.hasSelected) {
                obj.hasSelected = NO;
            }
        }];
         **/
        self.collectionBottomView.selectedAll = NO;
    }
    self.collectionBottomView.hidden = !_hiddenKeepView;
    [self.tableView reloadData];
}

/** 删除 */
- (void)deleteAction {
    /**
    if (_hiddenKeepView) {
        NSMutableArray * arr = [[NSMutableArray alloc] init];
        [self.tableView.dataArray enumerateObjectsUsingBlock:^(ArticleListDataModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.hasSelected) {
                [arr addObject:@(obj.contentId)];
            }
        }];
        if (arr.count > 0) {
            [SVProgressHUD showWithStatus:@"删除中……" maskType:SVProgressHUDMaskTypeBlack];
            NSString *deleteContentIdString = [arr componentsJoinedByString:@","];
            [ReadRequestManager newArticleDeleteCollectWithArticleId:deleteContentIdString sucess:^(id data) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                [self.tableView.mj_header beginRefreshing];
            } fail:^(NSString *error) {
                [SVProgressHUD showErrorWithStatus:error];
            }];
            return;
        } else {
            jxt_showAlertTitle(@"删除内容不能为空");
        }
    }
    
    self.collectionBottomView.hidden = !_hiddenKeepView;
    [self.tableView reloadData];
     **/
}

/** 全选 */
- (void)selectAllAction:(BOOL)select {
    /**
    [self.tableView.dataArray enumerateObjectsUsingBlock:^(ArticleListDataModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.hasSelected = select;
    }];
    [self.tableView reloadData];
     */
}

/** 更新全选按钮 */
- (void)updateSelectAllStatus {
    /**
    __block BOOL selectAll = NO;
    [self.tableView.dataArray enumerateObjectsUsingBlock:^(ArticleListDataModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!obj.hasSelected) {
            selectAll = NO;
            * stop = YES;
        } else {
            selectAll = YES;
        }
    }];
    self.collectionBottomView.selectedAll = selectAll;
     */
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UITableViewDataSource,UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row > self.tableView.dataArray.count - 1 ||  self.tableView.dataArray.count == 0) {
        return;
    }
    
    /**
    ArticleListDataModel * articleModel = tableView.dataArray[indexPath.row];
    if (_hiddenKeepView) {
        articleModel.hasSelected = !articleModel.hasSelected;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        [self updateSelectAllStatus];
    } else {
        articleModel.read_num += 1;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        NewReadArticleDetailViewController * readArticleDetailViewController = [[NewReadArticleDetailViewController alloc] init];
        readArticleDetailViewController.outsideListDataModel = articleModel;
        [APP.rootNavigationController pushViewController:readArticleDetailViewController animated:YES];
    }
     */
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableView.dataArray count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat tableCellHeight = 0;
    /**
    ArticleListDataModel *articleListDataModel = [tableView.dataArray objectAtIndex:indexPath.row];
    switch (articleListDataModel.listDataModelType) {
        case NewArticleListDataModelTypeNormal:
            tableCellHeight = [SomeoneZoneSectionTypeArticleCell cellHeightWithIndexPath:indexPath];
            break;
        default:
            tableCellHeight = [ArticleBigImageTypeCell cellHeightWithArticleListDataModel:(ArticleListDataModel *)articleListDataModel indexPath:indexPath];
            break;
    }
     */

    return tableCellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weakConfigure
    /**
    ArticleListDataModel * articleListDataModel = [tableView.dataArray objectAtIndex:indexPath.row];
    if (articleListDataModel.listDataModelType == NewArticleListDataModelTypeNormal) {
        // 单图靠右模式
        SomeoneZoneSectionTypeArticleCell *cell = [SomeoneZoneSectionTypeArticleCell initTableView:tableView];
        cell.indexPath = indexPath;
        cell.clickedCheckBlock = ^(NSIndexPath *indexPath) {
            [__weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        };
        
        return cell;
    } else {*/
        // 大图模式展示
        ArticleBigImageTypeCell *cell = [ArticleBigImageTypeCell initTableView:tableView];
        cell.indexPath = indexPath;
        cell.clickedCheckBlock = ^(NSIndexPath *indexPath) {
            [__weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        };
        return cell;
//    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.tag == 1000) {
            [obj removeFromSuperview];
        }
    }];
    
    /**
    ArticleListDataModel * articleListDataModel = [tableView.dataArray objectAtIndex:indexPath.row];
    if (articleListDataModel.listDataModelType == NewArticleListDataModelTypeNormal) {
        ((SomeoneZoneSectionTypeArticleCell *)cell).editAction = _hiddenKeepView;
        ((SomeoneZoneSectionTypeArticleCell *)cell).articleListDataModel = articleListDataModel;
    } else {
        //大图模式展示
        ((ArticleBigImageTypeCell *)cell).editAction = _hiddenKeepView;
        ((ArticleBigImageTypeCell *)cell).articleListDataModel = articleListDataModel;
    }
     */
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self setEditing:false animated:true];
}

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIImage * image = [UIImage imageNamed:@"cell_delete"];
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault image:image handler:^(UITableViewRowAction * _Nullable action, NSIndexPath * _Nullable indexPath) {
        [self deleteRowAction:indexPath];
    }];
    action1.backgroundColor = Color244;
    
    return @[action1];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 1100
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (@available(iOS 11.0, *)) {
        UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:nil handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            [self deleteRowAction:indexPath];
            completionHandler(YES);
        }];
        //也可以设置图片
        deleteAction.image = [UIImage imageNamed:@"cell_delete"];
        UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
        return config;
    } else {
        // Fallback on earlier versions
        return nil;
    }
}
#endif

/** 删除cell内容 */
- (void)deleteRowAction:(NSIndexPath *)indexPath {
    if (self.tableView.dataArray.count != 0) {
        [SVProgressHUD showWithStatus:@"删除中……" maskType:SVProgressHUDMaskTypeBlack];
        /**
        ArticleListDataModel * model = [self.tableView.dataArray objectAtIndex:indexPath.row];
        NSString *deleteContentIdString = [NSString stringWithFormat:@"%@", @(model.contentId)];
        [ReadRequestManager newArticleDeleteCollectWithArticleId:deleteContentIdString sucess:^(id data) {
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [self.tableView.dataArray removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
        } fail:^(NSString *error) {
            [self.tableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error];
        }];
         */
    }
}


#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.dataArray = [[NSMutableArray alloc] init];
        _tableView.backgroundColor = Color244;
        
        __weakConfigure
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __weakSelf.tableView.page = 1;
            [__weakSelf.tableView.dataArray removeAllObjects];
            [__weakSelf loadDataWithPage];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [__weakSelf loadDataWithPage];
        }];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.and.bottom.equalTo(self.view);
            make.top.equalTo(self.navigationView.mas_bottom);
        }];
    }
    return _tableView;
}
- (NullStateView *)nullStateView {
    if (!_nullStateView) {
        _nullStateView = [[NullStateView alloc] initWithFrame:self.tableView.frame fromViewType:CollectionListEmptyType];
        [self.view addSubview:_nullStateView];
    }
    return _nullStateView;
}
- (CollectionBottomView *)collectionBottomView {
    if (!_collectionBottomView) {
        _collectionBottomView = [[CollectionBottomView alloc] init];
        _collectionBottomView.backgroundColor = [UIColor whiteColor];
        _collectionBottomView.hidden = YES;
        [self.view addSubview:_collectionBottomView];
        [_collectionBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.and.bottom.equalTo(self.view);
            make.height.mas_equalTo(49);
        }];
        
        __weakConfigure
        _collectionBottomView.clickedDeleteActionBlock = ^{
            [__weakSelf deleteAction];
        };
        _collectionBottomView.clickedSelectedActionBlock = ^(BOOL select) {
            [__weakSelf selectAllAction:select];
        };
    }
    return _collectionBottomView;
}


@end
